package com.pcbly.web.components.email;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.MimeUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ReceiveAttach {
	protected final Log log = LogFactory.getLog(getClass());
	protected String saveAttachPath = ""; // 附件下载后的存放目录
	
	protected String realPath="";
	
	

	public String getRealPath() {
		return realPath;
	}

	public void setRealPath(String realPath) {
		this.realPath = realPath;
	}

	public String getSaveAttachPath() {
		return saveAttachPath;
	}

	public void setSaveAttachPath(String saveAttachPath) {
		this.saveAttachPath = saveAttachPath;
	}

	/**
	 * 【保存附件】
	 */
	protected String saveAttachMent(Part part) throws Exception {
		String fileName = "";
		String treturn = "";
	
		if (part.isMimeType("multipart/*")) {
			Multipart mp = (Multipart) part.getContent();
			for (int i = 0; i < mp.getCount(); i++) {
				BodyPart mpart = mp.getBodyPart(i);
				String disposition = mpart.getDisposition(); 
				log.debug("disposition :::::::::::::::::::::" + disposition); 
				log.debug("contentType :::::::::::::::::::::"+ mpart.getContentType());
				if ((disposition != null)
						&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
								.equals(Part.INLINE)))) {
					fileName = mpart.getFileName(); 
					log.debug("fileName1 :::::::::::::::::::::" + fileName);
					if (fileName != null) {
						if (fileName.toLowerCase().indexOf("gb2312") != -1) {
							fileName = MimeUtility.decodeText(fileName);
						}
						fileName = fileChange(fileName);
						treturn += saveFile(fileName, mpart.getInputStream());
					}

				} else if (mpart.isMimeType("multipart/*")) {
					treturn +=saveAttachMent(mpart);
				} else {

					fileName = mpart.getFileName(); 
					log.debug("fileName2 :::::::::::::::::::::" + fileName);
					if (fileName != null) {
						if (fileName.toLowerCase().indexOf("gb2312") != -1) {
							fileName = MimeUtility.decodeText(fileName);
						}
						fileName = fileChange(fileName);
						treturn += saveFile(fileName, mpart.getInputStream());
					}
				}
			}
		} else if (part.isMimeType("message/rfc822")) {
			treturn +=saveAttachMent((Part) part.getContent());
		}
		return treturn;
	}
	protected Date getSentDate(Message message) throws Exception {
		Date sentdate = message.getSentDate(); 
		return sentdate;
	} 
	private String fileChange(String fileName) {
		String temp = "";
		boolean iflag = false;
		String[] arrays={"\\","/",":","*","?","<",">","|"};
		for(String string:arrays){
			if (fileName.indexOf(string) >= 0) {
				iflag = true;
				break;
			}
		}
		 
		temp = "F" + System.currentTimeMillis(); 
		if(!iflag){
			temp+=fileName;
		}
		return temp;
	}

	/**
	 * 【真正的保存附件到指定目录里】
	 */
	protected String saveFile(String fileName, InputStream in) throws Exception {
   
		String treturn = realPath + "//" + fileName;
		File storefile = new File(treturn); 
		treturn=saveAttachPath+ "//" + fileName; 
//		if(!storefile.exists()){
//			storefile.mkdirs();
//		}
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(storefile));
			bis = new BufferedInputStream(in);
			int c;
			while ((c = bis.read()) != -1) {
				bos.write(c);
				bos.flush();
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			log.error(exception.getMessage());
			throw new Exception("文件保存失败!");
		} finally {
			bos.close();
			bis.close();
			// return treturn;
		}
		return treturn;
	}

	/**
	 * 判断此邮件是否包含附件
	 */
	protected boolean isContainAttach(Part part) throws Exception {
		boolean attachflag = false;
		if (part.isMimeType("multipart/*")) {
			Multipart mp = (Multipart) part.getContent();
			for (int i = 0; i < mp.getCount(); i++) {
				BodyPart mpart = mp.getBodyPart(i);
				String disposition = mpart.getDisposition();
				if ((disposition != null)
						&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
								.equals(Part.INLINE))))
					attachflag = true;
				else if (mpart.isMimeType("multipart/*")) {
					attachflag = isContainAttach((Part) mpart);
				} else {
					String contype = mpart.getContentType();
					if (contype.toLowerCase().indexOf("application") != -1)
						attachflag = true;
					if (contype.toLowerCase().indexOf("name") != -1)
						attachflag = true;
				}
			}
		} else if (part.isMimeType("message/rfc822")) {
			attachflag = isContainAttach((Part) part.getContent());
		}
		return attachflag;
	}
}
